import struct
from collections import OrderedDict

from ..base import BaseParser


class GetCompanyInfoCategory(BaseParser):

    def setParams(self, market, code):
        code = code.encode('utf-8') if type(code) is str else code

        pkg = bytearray.fromhex(u'0c 0f 10 9b 00 01 0e 00 0e 00 cf 02')
        pkg.extend(struct.pack(u'<H6sI', market, code, 0))

        self.send_pkg = pkg

    def parseResponse(self, body_buf):

        (num,) = struct.unpack('<H', body_buf[:2])

        def get_str(b):
            p = b.find(b'\x00')

            if p != -1:
                b = b[0: p]

            n = 'unkown_str'

            try:
                return b.decode('gbk')
            except(AttributeError, LookupError) as e:
                return n

        # 初始化参数
        category = []

        # 初始化解析位置
        pos = 2

        for i in range(num):
            (name, filename, start, length) = struct.unpack(u'<64s80sII', body_buf[pos: pos + 152])
            pos += 152

            entry = OrderedDict(
                [
                    ('name', get_str(name)),
                    ('filename', get_str(filename)),
                    ('start', start),
                    ('length', length),
                ]
            )

            category.append(entry)

        return category
